package com.example.gui.javafxdemo;

import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import java.util.Random;

public class MainApp extends Application {

    @Override
    public void start(Stage stage) {
        WebView webView = new WebView();
        WebEngine engine = webView.getEngine();

        // 页面加载完再注入 Java 对象
        engine.getLoadWorker().stateProperty().addListener((ov, oldV, newV) -> {
            if (newV == Worker.State.SUCCEEDED) {
                var win = (netscape.javascript.JSObject) engine.executeScript("window");
                var adapter = new JsAdapter(engine);
                win.setMember("java", adapter);

                // 模拟每秒推送数据
                var timer = new java.util.Timer();
                timer.scheduleAtFixedRate(new java.util.TimerTask() {
                    final Random rnd = new Random();
                    public void run() {
                        adapter.pushData(rnd.nextInt(100));
                    }
                }, 0, 1000);
            }
        });

        engine.load(getClass().getResource("/chart.html").toExternalForm());

        stage.setScene(new Scene(webView, 650, 400));
        stage.setTitle("JavaFX ←→ JS 实时交互");
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}